#{extends 'main.html' /}
#{set title:'Chat room' /}

<h1>Haz ingresado como ${user} <a href="@{Secure.logout()}">Salir</a></h1> 

<div id="thread">
    <script type="text/html" id="message_tmpl">
        <% if(event.type == 'message') { %>
            <div class="message <%= event.user == '${user}' ? 'you' : '' %>">
                <h2><%= event.user %></h2>
                <p>
                    <%= event.text %>
                </p>
            </div>
        <% } %>
        <% if(event.type == 'join') { %>
            <div class="message notice">
                <h2></h2>
                <p>
                    <%= event.user %> ingresó
                </p>
            </div>
        <% } %>
        <% if(event.type == 'leave') { %>
            <div class="message notice">
                <h2></h2>
                <p>
                    <%= event.user %> salió
                </p>
            </div>
        <% } %>
        <% if(event.type == 'quit') { %>
            <div class="message important">
                <h2></h2>
                <p>
                    Haz salido!
                </p>
            </div>
        <% } %>
    </script>
</div>

<div id="newMessage">
    <input type="text" id="message" autocomplete="off">
    <input type="submit" value="Enviar" id="send">
</div>

<script type="text/javascript">

    // Create a socket
    var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
    var socket = new WS('@@{Application.ChatRoomSocket.join(user)}')
    
    // Display a message
    var display = function(event) {
        $('#thread').append(tmpl('message_tmpl', {event: event}));
        $('#thread').scrollTo('max')
    }
    
    // Message received on the socket
    socket.onmessage = function(event) {
        var parts = /^([^:]+):([^:]+)(:(.*))?$/.exec(event.data)
        display({
            type: parts[1],
            user: parts[2],
            text: parts[4]
        })
    }
    
    $('#send').click(function(e) {
        var message = $('#message').val()
        $('#message').val('')
        socket.send(message)
    });
    
    $('#message').keypress(function(e) {
        if(e.charCode == 13 || e.keyCode == 13) {
            $('#send').click()
            e.preventDefault()
        }
    })
    
</script>
